package com.tbynet.jwp.repository.impl;

import java.math.BigInteger;
import java.util.*;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.tbynet.jwp.framework.aop.Aop;
import com.tbynet.jwp.framework.core._JwpServiceProvider;
import com.tbynet.jwp.model.Usermeta;
import com.tbynet.jwp.model.Users;
import com.tbynet.jwp.repository.spi.UserService;

/**
 * 用户服务实现类 - 完整实现版
 */
@Aop(UserService.class)
public class UserServiceImpl extends _JwpServiceProvider<Users> implements UserService {

    /** 用户元数据DAO对象 */
    private Usermeta usermetaDao = new Usermeta().dao();

    /** 常量定义 */
    private static final String USERMETA_TABLE = "wp_usermeta";
    private static final String POSTS_TABLE = "wp_posts";
    private static final String COMMENTS_TABLE = "wp_comments";

    // ========== 重写基类方法 ==========

    @Override
    protected String buildSearchWhereSql(String keyword, List<Object> params) {
        StringBuilder whereSql = new StringBuilder(" WHERE 1=1");
        if (StrKit.notBlank(keyword)) {
            whereSql.append(" AND (user_login LIKE ? OR user_email LIKE ? OR display_name LIKE ? OR user_nicename LIKE ?)");
            String likeKeyword = "%" + keyword + "%";
            params.add(likeKeyword);
            params.add(likeKeyword);
            params.add(likeKeyword);
            params.add(likeKeyword);
        }
        return whereSql.toString();
    }

    @Override
    protected String getDefaultOrderBy() {
        return "user_registered DESC, ID DESC";
    }

    @Override
    protected String getBasicFields() {
        return "ID, user_login, user_email, display_name, user_registered, user_status, user_nicename";
    }

    // ========== WordPress 核心用户CRUD操作 ==========

    @Override
    public Object createUser(Users user) {
        return executeWithResultLogging("createUser", () -> {
            validateNotNull(user, "用户对象不能为空");

            // 设置默认值
            if (user.getUserRegistered() == null) {
                user.setUserRegistered(new Date());
            }
            if (user.getUserStatus() == null) {
                user.setUserStatus(0);
            }
            if (StrKit.isBlank(user.getUserNicename())) {
                user.setUserNicename(user.getUserLogin());
            }

            boolean success = user.save();
            return success ? user.getID() : null;
        }, user.getUserLogin());
    }

    @Override
    public boolean deleteUser(Object userId, Object reassignTo) {
        return executeWithBooleanLogging("deleteUser", () -> {
            validateNotNull(userId, "用户ID不能为空");

            // 如果指定了重新分配用户，先重新分配内容
            if (reassignTo != null) {
                reassignUserContent(userId, reassignTo);
            }

            // 删除用户元数据
            deleteAllUserMetas(userId);

            // 删除用户会话数据（如果存在）
            clearUserSessions(userId);

            // 删除用户
            return deleteById(userId);
        }, userId, reassignTo);
    }

    // ========== WordPress 用户查询方法 ==========

    @Override
    public Users findUserByLoginOrEmail(String loginOrEmail) {
        return executeWithResultLogging("findUserByLoginOrEmail", () -> {
            validateNotBlank(loginOrEmail, "用户名或邮箱不能为空");

            return getDao().findFirst(
                    "SELECT * FROM " + getTableName() +
                            " WHERE user_login = ? OR user_email = ? LIMIT 1",
                    loginOrEmail, loginOrEmail
            );
        }, loginOrEmail);
    }

    @Override
    public Users findUserByLogin(String userLogin) {
        return executeWithResultLogging("findUserByLogin", () -> {
            validateNotBlank(userLogin, "用户名不能为空");

            return getDao().findFirst(
                    "SELECT * FROM " + getTableName() + " WHERE user_login = ? LIMIT 1",
                    userLogin
            );
        }, userLogin);
    }

    @Override
    public Users findUserByEmail(String email) {
        return executeWithResultLogging("findUserByEmail", () -> {
            validateNotBlank(email, "邮箱不能为空");

            return getDao().findFirst(
                    "SELECT * FROM " + getTableName() + " WHERE user_email = ? LIMIT 1",
                    email
            );
        }, email);
    }

    @Override
    public Users findUserByNickname(String nickname) {
        return executeWithResultLogging("findUserByNickname", () -> {
            validateNotBlank(nickname, "昵称不能为空");

            String sql = "SELECT u.* FROM " + getTableName() + " u " +
                    "INNER JOIN " + USERMETA_TABLE + " um ON u.ID = um.user_id " +
                    "WHERE um.meta_key = 'nickname' AND um.meta_value = ? LIMIT 1";
            return getDao().findFirst(sql, nickname);
        }, nickname);
    }

    @Override
    public List<Users> findUsersByDisplayName(String displayName) {
        return executeWithResultLogging("findUsersByDisplayName", () -> {
            validateNotBlank(displayName, "显示名称不能为空");

            return getDao().find(
                    "SELECT * FROM " + getTableName() + " WHERE display_name LIKE ? ORDER BY " + getDefaultOrderBy(),
                    "%" + displayName + "%"
            );
        }, displayName);
    }

    @Override
    public Users findUserByActivationKey(String activationKey) {
        return executeWithResultLogging("findUserByActivationKey", () -> {
            validateNotBlank(activationKey, "激活密钥不能为空");

            return getDao().findFirst(
                    "SELECT * FROM " + getTableName() + " WHERE user_activation_key = ? LIMIT 1",
                    activationKey
            );
        }, activationKey);
    }

    @Override
    public List<Users> findUsersByStatus(Integer userStatus) {
        return executeWithResultLogging("findUsersByStatus", () -> {
            validateNotNull(userStatus, "用户状态不能为空");

            return getDao().find(
                    "SELECT * FROM " + getTableName() + " WHERE user_status = ? ORDER BY " + getDefaultOrderBy(),
                    userStatus
            );
        }, userStatus);
    }

    // ========== WordPress 存在性检查 ==========

    @Override
    public boolean isUserLoginExists(String userLogin) {
        return existsByField("user_login", userLogin);
    }

    @Override
    public boolean isEmailExists(String email) {
        return existsByField("user_email", email);
    }

    @Override
    public boolean isUserIdExists(Object userId) {
        return existsById(userId);
    }

    // ========== WordPress 用户统计 ==========

    @Override
    public long getUserCountByStatus(Integer status) {
        return executeWithResultLogging("getUserCountByStatus", () -> {
            String sql = "SELECT COUNT(*) FROM " + getTableName() + " WHERE user_status = ?";
            Long count = Db.queryLong(sql, status);
            return count != null ? count : 0;
        }, status);
    }

    @Override
    public Map<String, Object> getUserRoleStats() {
        return executeWithResultLogging("getUserRoleStats", () -> {
            String sql = "SELECT um.meta_value as role, COUNT(*) as count " +
                    "FROM " + USERMETA_TABLE + " um " +
                    "WHERE um.meta_key = 'wp_capabilities' " +
                    "GROUP BY um.meta_value";

            List<Record> records = Db.find(sql);
            Map<String, Object> stats = new HashMap<>();

            for (Record record : records) {
                String role = record.getStr("role");
                Long count = record.getLong("count");
                stats.put(role, count);
            }

            // 添加总计
            stats.put("total_users", getCount());
            return stats;
        });
    }

    @Override
    public Map<String, Object> getUserRegistrationStats(int days) {
        return executeWithResultLogging("getUserRegistrationStats", () -> {
            String sql = "SELECT DATE(user_registered) as reg_date, COUNT(*) as count " +
                    "FROM " + getTableName() + " " +
                    "WHERE user_registered >= DATE_SUB(NOW(), INTERVAL ? DAY) " +
                    "GROUP BY DATE(user_registered) " +
                    "ORDER BY reg_date DESC";

            List<Record> records = Db.find(sql, days);
            Map<String, Object> stats = new LinkedHashMap<>();

            long total = 0;
            for (Record record : records) {
                String date = record.getStr("reg_date");
                Long count = record.getLong("count");
                stats.put(date, count);
                total += count != null ? count : 0;
            }

            stats.put("total", total);
            stats.put("period_days", days);
            return stats;
        }, days);
    }

    // ========== WordPress 批量操作 ==========

    @Override
    public int batchDeleteUsers(List<Object> userIds, Object reassignTo) {
        return executeWithResultLogging("batchDeleteUsers", () -> {
            if (userIds == null || userIds.isEmpty()) {
                return 0;
            }

            int successCount = 0;
            for (Object userId : userIds) {
                if (deleteUser(userId, reassignTo)) {
                    successCount++;
                }
            }

            return successCount;
        }, userIds.size(), reassignTo);
    }

    @Override
    public int batchUpdateUserRole(List<BigInteger> userIds, String role) {
        return executeWithResultLogging("batchUpdateUserRole", () -> {
            if (userIds == null || userIds.isEmpty() || StrKit.isBlank(role)) {
                return 0;
            }

            int successCount = 0;
            for (BigInteger userId : userIds) {
                if (setUserRole(userId, role)) {
                    successCount++;
                }
            }

            return successCount;
        }, userIds.size(), role);
    }

    @Override
    public int batchUpdateUserStatus(List<Object> userIds, Integer status) {
        return executeWithResultLogging("batchUpdateUserStatus", () -> {
            if (userIds == null || userIds.isEmpty() || status == null) {
                return 0;
            }

            String placeholders = String.join(",", Collections.nCopies(userIds.size(), "?"));
            String sql = "UPDATE " + getTableName() + " SET user_status = ? WHERE ID IN (" + placeholders + ")";

            List<Object> params = new ArrayList<>();
            params.add(status);
            params.addAll(userIds);

            int result = Db.update(sql, params.toArray());
            return result;
        }, userIds.size(), status);
    }

    // ========== 用户元数据操作实现 ==========

    @Override
    public List<Usermeta> getUserMetas(Object userId) {
        return executeWithResultLogging("getUserMetas", () -> {
            validateNotNull(userId, "用户ID不能为空");

            return usermetaDao.find(
                    "SELECT * FROM " + USERMETA_TABLE + " WHERE user_id = ? ORDER BY umeta_id",
                    userId
            );
        }, userId);
    }

    @Override
    public Usermeta getUserMeta(Object userId, String metaKey) {
        return executeWithResultLogging("getUserMeta", () -> {
            validateNotNull(userId, "用户ID不能为空");
            validateNotBlank(metaKey, "元数据键不能为空");

            return usermetaDao.findFirst(
                    "SELECT * FROM " + USERMETA_TABLE + " WHERE user_id = ? AND meta_key = ? LIMIT 1",
                    userId, metaKey
            );
        }, userId, metaKey);
    }

    @Override
    public List<Usermeta> getUserMetasByKeys(Object userId, String... metaKeys) {
        return executeWithResultLogging("getUserMetasByKeys", () -> {
            validateNotNull(userId, "用户ID不能为空");

            if (metaKeys == null || metaKeys.length == 0) {
                return getUserMetas(userId);
            }

            List<Object> params = new ArrayList<>();
            StringBuilder sqlBuilder = new StringBuilder("SELECT * FROM " + USERMETA_TABLE + " WHERE user_id = ?");
            params.add(userId);

            sqlBuilder.append(" AND meta_key IN (");
            for (int i = 0; i < metaKeys.length; i++) {
                if (i > 0) {
                    sqlBuilder.append(",");
                }
                sqlBuilder.append("?");
                params.add(metaKeys[i]);
            }
            sqlBuilder.append(") ORDER BY umeta_id");

            return usermetaDao.find(sqlBuilder.toString(), params.toArray());
        }, userId, metaKeys.length);
    }

    @Override
    public String getUserMetaValue(Object userId, String metaKey) {
        return getUserMetaValue(userId, metaKey, "");
    }

    @Override
    public String getUserMetaValue(Object userId, String metaKey, String defaultValue) {
        Usermeta meta = getUserMeta(userId, metaKey);
        return meta != null && meta.getMetaValue() != null ? meta.getMetaValue() : defaultValue;
    }

    @Override
    public boolean saveUsermeta(Usermeta usermeta) {
        return executeWithBooleanLogging("saveUsermeta", () -> {
            validateNotNull(usermeta, "元数据对象不能为空");
            return usermeta.save();
        }, usermeta.getUserId(), usermeta.getMetaKey());
    }

    @Override
    public boolean updateUsermeta(Usermeta usermeta) {
        return executeWithBooleanLogging("updateUsermeta", () -> {
            validateNotNull(usermeta, "元数据对象不能为空");
            validateNotNull(usermeta.getUmetaId(), "元数据ID不能为空");
            return usermeta.update();
        }, usermeta.getUmetaId());
    }

    @Override
    public boolean deleteUserMeta(Object userId, String metaKey) {
        return executeWithBooleanLogging("deleteUserMeta", () -> {
            validateNotNull(userId, "用户ID不能为空");
            validateNotBlank(metaKey, "元数据键不能为空");

            String sql = "DELETE FROM " + USERMETA_TABLE + " WHERE user_id = ? AND meta_key = ?";
            return Db.delete(sql, userId, metaKey) > 0;
        }, userId, metaKey);
    }

    @Override
    public boolean deleteAllUserMetas(Object userId) {
        return executeWithBooleanLogging("deleteAllUserMetas", () -> {
            validateNotNull(userId, "用户ID不能为空");

            String sql = "DELETE FROM " + USERMETA_TABLE + " WHERE user_id = ?";
            int result = Db.delete(sql, userId);
            return result >= 0;
        }, userId);
    }

    @Override
    public boolean saveOrUpdateUsermeta(Usermeta usermeta) {
        return executeWithBooleanLogging("saveOrUpdateUsermeta", () -> {
            validateNotNull(usermeta, "元数据对象不能为空");

            Usermeta existingMeta = getUserMeta(usermeta.getUserId(), usermeta.getMetaKey());

            if (existingMeta != null) {
                usermeta.setUmetaId(existingMeta.getUmetaId());
                return updateUsermeta(usermeta);
            } else {
                return saveUsermeta(usermeta);
            }
        }, usermeta.getUserId(), usermeta.getMetaKey());
    }

    @Override
    public int batchUpdateUserMetas(BigInteger userId, Map<String, String> metaData) {
        return executeWithResultLogging("batchUpdateUserMetas", () -> {
            if (userId == null || metaData == null || metaData.isEmpty()) {
                return 0;
            }

            int successCount = 0;
            for (Map.Entry<String, String> entry : metaData.entrySet()) {
                Usermeta meta = new Usermeta();
                meta.setUserId(userId);
                meta.setMetaKey(entry.getKey());
                meta.setMetaValue(entry.getValue());

                if (saveOrUpdateUsermeta(meta)) {
                    successCount++;
                }
            }

            return successCount;
        }, userId, metaData.size());
    }

    @Override
    public int batchDeleteUserMetas(Object userId, List<String> metaKeys) {
        return executeWithResultLogging("batchDeleteUserMetas", () -> {
            if (userId == null || metaKeys == null || metaKeys.isEmpty()) {
                return 0;
            }

            String placeholders = String.join(",", Collections.nCopies(metaKeys.size(), "?"));
            String sql = "DELETE FROM " + USERMETA_TABLE + " WHERE user_id = ? AND meta_key IN (" + placeholders + ")";

            List<Object> params = new ArrayList<>();
            params.add(userId);
            params.addAll(metaKeys);

            int result = Db.delete(sql, params.toArray());
            return result;
        }, userId, metaKeys.size());
    }

    // ========== WordPress 用户角色和能力 ==========

    @Override
    public List<String> getUserCapabilities(Object userId) {
        return executeWithResultLogging("getUserCapabilities", () -> {
            String capabilitiesJson = getUserMetaValue(userId, "wp_capabilities");
            List<String> capList = new ArrayList<>();

            if (StrKit.notBlank(capabilitiesJson)) {
                try {
                    // 简化解析WordPress能力JSON格式
                    // 实际格式类似: {"administrator":true,"edit_posts":true}
                    capabilitiesJson = capabilitiesJson.replace("{", "").replace("}", "").replace("\"", "");
                    String[] pairs = capabilitiesJson.split(",");

                    for (String pair : pairs) {
                        String[] keyValue = pair.split(":");
                        if (keyValue.length == 2 && "true".equals(keyValue[1].trim())) {
                            capList.add(keyValue[0].trim());
                        }
                    }
                } catch (Exception e) {
                    log.error("解析用户能力JSON失败: " + capabilitiesJson, e);
                }
            }

            // 添加默认能力
            if (capList.isEmpty()) {
                capList.add("read");
            }

            return capList;
        }, userId);
    }

    @Override
    public boolean hasCapability(Object userId, String capability) {
        List<String> capabilities = getUserCapabilities(userId);
        return capabilities.contains(capability);
    }

    @Override
    public String getUserRole(Object userId) {
        return executeWithResultLogging("getUserRole", () -> {
            List<String> capabilities = getUserCapabilities(userId);

            // WordPress角色检测逻辑
            if (capabilities.contains("administrator")) return "administrator";
            if (capabilities.contains("editor")) return "editor";
            if (capabilities.contains("author")) return "author";
            if (capabilities.contains("contributor")) return "contributor";
            if (capabilities.contains("subscriber")) return "subscriber";

            return "subscriber"; // 默认角色
        }, userId);
    }

    @Override
    public boolean setUserRole(BigInteger userId, String role) {
        return executeWithBooleanLogging("setUserRole", () -> {
            validateNotNull(userId, "用户ID不能为空");
            validateNotBlank(role, "角色不能为空");

            // WordPress角色存储格式
            String roleData = "{\"" + role + "\":true}";

            Usermeta meta = new Usermeta();
            meta.setUserId(userId);
            meta.setMetaKey("wp_capabilities");
            meta.setMetaValue(roleData);

            return saveOrUpdateUsermeta(meta);
        }, userId, role);
    }

    @Override
    public boolean addUserCapability(BigInteger userId, String capability) {
        return executeWithBooleanLogging("addUserCapability", () -> {
            validateNotNull(userId, "用户ID不能为空");
            validateNotBlank(capability, "能力名称不能为空");

            List<String> capabilities = getUserCapabilities(userId);
            if (!capabilities.contains(capability)) {
                capabilities.add(capability);
                return updateCapabilities(userId, capabilities);
            }
            return true; // 已经存在
        }, userId, capability);
    }

    @Override
    public boolean removeUserCapability(BigInteger userId, String capability) {
        return executeWithBooleanLogging("removeUserCapability", () -> {
            validateNotNull(userId, "用户ID不能为空");
            validateNotBlank(capability, "能力名称不能为空");

            List<String> capabilities = getUserCapabilities(userId);
            if (capabilities.remove(capability)) {
                return updateCapabilities(userId, capabilities);
            }
            return true; // 本来就不存在
        }, userId, capability);
    }

    @Override
    public boolean hasAnyCapability(Object userId, String... capabilities) {
        List<String> userCapabilities = getUserCapabilities(userId);
        return Arrays.stream(capabilities).anyMatch(userCapabilities::contains);
    }

    @Override
    public boolean hasAllCapabilities(Object userId, String... capabilities) {
        List<String> userCapabilities = getUserCapabilities(userId);
        return Arrays.stream(capabilities).allMatch(userCapabilities::contains);
    }

    // ========== WordPress 用户认证和密码 ==========

    @Override
    public boolean validatePassword(String userLogin, String password) {
        return executeWithBooleanLogging("validatePassword", () -> {
            validateNotBlank(userLogin, "用户名不能为空");
            validateNotBlank(password, "密码不能为空");

            Users user = findUserByLogin(userLogin);
            if (user == null) {
                return false;
            }

            String storedPassword = user.getUserPass();
            // 简化密码验证，实际应该使用WordPress的密码哈希验证
            // 这里假设是明文密码（仅用于演示）
            return storedPassword != null && storedPassword.equals(password);
        }, userLogin);
    }

    @Override
    public boolean updatePassword(BigInteger userId, String newPassword) {
        return executeWithBooleanLogging("updatePassword", () -> {
            validateNotNull(userId, "用户ID不能为空");
            validateNotBlank(newPassword, "新密码不能为空");

            Users user = getById(userId);
            if (user == null) {
                return false;
            }

            // 这里应该使用WordPress的密码加密
            user.setUserPass(newPassword);
            return update(user);
        }, userId);
    }

    @Override
    public String generatePasswordResetKey(BigInteger userId) {
        return executeWithResultLogging("generatePasswordResetKey", () -> {
            validateNotNull(userId, "用户ID不能为空");

            String resetKey = UUID.randomUUID().toString().replace("-", "");

            // 保存重置密钥到用户元数据
            Usermeta meta = new Usermeta();
            meta.setUserId(userId);
            meta.setMetaKey("password_reset_key");
            meta.setMetaValue(resetKey);

            if (saveOrUpdateUsermeta(meta)) {
                return resetKey;
            }

            return "";
        }, userId);
    }

    @Override
    public boolean validatePasswordResetKey(Object userId, String resetKey) {
        return executeWithBooleanLogging("validatePasswordResetKey", () -> {
            validateNotNull(userId, "用户ID不能为空");
            validateNotBlank(resetKey, "重置密钥不能为空");

            String storedKey = getUserMetaValue(userId, "password_reset_key");
            return resetKey.equals(storedKey);
        }, userId, resetKey);
    }

    @Override
    public boolean clearUserSessions(Object userId) {
        return executeWithBooleanLogging("clearUserSessions", () -> {
            validateNotNull(userId, "用户ID不能为空");

            // 删除会话相关的元数据
            boolean success1 = deleteUserMeta(userId, "session_tokens");
            boolean success2 = deleteUserMeta(userId, "password_reset_key");

            return success1 || success2;
        }, userId);
    }

    @Override
    public List<Map<String, Object>> getUserLoginHistory(Object userId) {
        return executeWithResultLogging("getUserLoginHistory", () -> {
            validateNotNull(userId, "用户ID不能为空");

            String loginHistory = getUserMetaValue(userId, "login_history");
            List<Map<String, Object>> history = new ArrayList<>();

            if (StrKit.notBlank(loginHistory)) {
                try {
                    // 简化解析登录历史
                    String[] entries = loginHistory.split(";");
                    for (String entry : entries) {
                        String[] parts = entry.split(",");
                        if (parts.length >= 2) {
                            Map<String, Object> historyEntry = new HashMap<>();
                            historyEntry.put("timestamp", parts[0]);
                            historyEntry.put("ip", parts[1]);
                            historyEntry.put("user_agent", parts.length > 2 ? parts[2] : "");
                            history.add(historyEntry);
                        }
                    }
                } catch (Exception e) {
                    log.error("解析登录历史失败", e);
                }
            }

            return history;
        }, userId);
    }

    // ========== WordPress 高级查询 ==========

    @Override
    public List<Users> getUsersPaged(int pageNumber, int pageSize, String orderBy, String order) {
        return executeWithResultLogging("getUsersPaged", () -> {
            int offset = (pageNumber - 1) * pageSize;
            String actualOrderBy = StrKit.notBlank(orderBy) ? orderBy : "user_registered";
            String actualOrder = "DESC".equalsIgnoreCase(order) ? "DESC" : "ASC";

            String sql = "SELECT * FROM " + getTableName() +
                    " ORDER BY " + actualOrderBy + " " + actualOrder +
                    " LIMIT ? OFFSET ?";

            return getDao().find(sql, pageSize, offset);
        }, pageNumber, pageSize, orderBy, order);
    }

    @Override
    public List<Users> searchUsers(String searchTerm) {
        return executeWithResultLogging("searchUsers", () -> {
            if (StrKit.isBlank(searchTerm)) {
                return getAll();
            }

            String sql = "SELECT * FROM " + getTableName() +
                    " WHERE user_login LIKE ? OR user_email LIKE ? OR display_name LIKE ? OR user_nicename LIKE ?" +
                    " ORDER BY " + getDefaultOrderBy();

            String likeTerm = "%" + searchTerm + "%";
            return getDao().find(sql, likeTerm, likeTerm, likeTerm, likeTerm);
        }, searchTerm);
    }

    @Override
    public List<Users> searchUsersAdvanced(Map<String, Object> conditions) {
        return findList(conditions);
    }

    @Override
    public List<Users> findUsersByMetaValue(String metaKey, String metaValue) {
        return executeWithResultLogging("findUsersByMetaValue", () -> {
            validateNotBlank(metaKey, "元数据键不能为空");

            String sql = "SELECT u.* FROM " + getTableName() + " u " +
                    "INNER JOIN " + USERMETA_TABLE + " um ON u.ID = um.user_id " +
                    "WHERE um.meta_key = ?";

            List<Object> params = new ArrayList<>();
            params.add(metaKey);

            if (metaValue != null) {
                sql += " AND um.meta_value = ?";
                params.add(metaValue);
            }

            sql += " ORDER BY " + getDefaultOrderBy();

            return getDao().find(sql, params.toArray());
        }, metaKey, metaValue);
    }

    @Override
    public List<Users> findUsersByRegistrationDate(Date startDate, Date endDate) {
        return executeWithResultLogging("findUsersByRegistrationDate", () -> {
            validateNotNull(startDate, "开始日期不能为空");
            validateNotNull(endDate, "结束日期不能为空");

            return getDao().find(
                    "SELECT * FROM " + getTableName() +
                            " WHERE user_registered BETWEEN ? AND ? ORDER BY user_registered",
                    startDate, endDate
            );
        }, startDate, endDate);
    }

    @Override
    public List<Users> findUsersByLastLogin(int days) {
        return executeWithResultLogging("findUsersByLastLogin", () -> {
            String sql = "SELECT u.* FROM " + getTableName() + " u " +
                    "INNER JOIN " + USERMETA_TABLE + " um ON u.ID = um.user_id " +
                    "WHERE um.meta_key = 'last_login' AND um.meta_value >= DATE_SUB(NOW(), INTERVAL ? DAY) " +
                    "ORDER BY um.meta_value DESC";

            return getDao().find(sql, days);
        }, days);
    }

    @Override
    public List<Users> findUsersByRole(String role) {
        return executeWithResultLogging("findUsersByRole", () -> {
            validateNotBlank(role, "角色不能为空");

            String sql = "SELECT u.* FROM " + getTableName() + " u " +
                    "INNER JOIN " + USERMETA_TABLE + " um ON u.ID = um.user_id " +
                    "WHERE um.meta_key = 'wp_capabilities' AND um.meta_value LIKE ? " +
                    "ORDER BY " + getDefaultOrderBy();

            return getDao().find(sql, "%" + role + "%");
        }, role);
    }

    // ========== WordPress 用户内容关联 ==========

    @Override
    public long getUserPostCount(Object userId) {
        return executeWithResultLogging("getUserPostCount", () -> {
            validateNotNull(userId, "用户ID不能为空");

            String sql = "SELECT COUNT(*) FROM " + POSTS_TABLE + " WHERE post_author = ? AND post_type = 'post'";
            Long count = Db.queryLong(sql, userId);
            return count != null ? count : 0;
        }, userId);
    }

    @Override
    public long getUserPostCountByStatus(Object userId, String postStatus) {
        return executeWithResultLogging("getUserPostCountByStatus", () -> {
            validateNotNull(userId, "用户ID不能为空");
            validateNotBlank(postStatus, "文章状态不能为空");

            String sql = "SELECT COUNT(*) FROM " + POSTS_TABLE + " WHERE post_author = ? AND post_type = 'post' AND post_status = ?";
            Long count = Db.queryLong(sql, userId, postStatus);
            return count != null ? count : 0;
        }, userId, postStatus);
    }

    @Override
    public long getUserCommentCount(Object userId) {
        return executeWithResultLogging("getUserCommentCount", () -> {
            validateNotNull(userId, "用户ID不能为空");

            String sql = "SELECT COUNT(*) FROM " + COMMENTS_TABLE + " WHERE user_id = ?";
            Long count = Db.queryLong(sql, userId);
            return count != null ? count : 0;
        }, userId);
    }

    @Override
    public boolean reassignUserContent(Object fromUserId, Object toUserId) {
        return executeWithBooleanLogging("reassignUserContent", () -> {
            validateNotNull(fromUserId, "原用户ID不能为空");
            validateNotNull(toUserId, "目标用户ID不能为空");

            // 重新分配文章
            String updatePosts = "UPDATE " + POSTS_TABLE + " SET post_author = ? WHERE post_author = ?";
            int postsUpdated = Db.update(updatePosts, toUserId, fromUserId);

            // 重新分配页面
            String updatePages = "UPDATE " + POSTS_TABLE + " SET post_author = ? WHERE post_author = ? AND post_type = 'page'";
            int pagesUpdated = Db.update(updatePages, toUserId, fromUserId);

            // 重新分配媒体
            String updateMedia = "UPDATE " + POSTS_TABLE + " SET post_author = ? WHERE post_author = ? AND post_type = 'attachment'";
            int mediaUpdated = Db.update(updateMedia, toUserId, fromUserId);

            log.debug("重新分配用户内容完成: 文章{}篇, 页面{}个, 媒体{}个", postsUpdated, pagesUpdated, mediaUpdated);
            return true;
        }, fromUserId, toUserId);
    }

    @Override
    public long getUserMediaCount(Object userId) {
        return executeWithResultLogging("getUserMediaCount", () -> {
            validateNotNull(userId, "用户ID不能为空");

            String sql = "SELECT COUNT(*) FROM " + POSTS_TABLE + " WHERE post_author = ? AND post_type = 'attachment'";
            Long count = Db.queryLong(sql, userId);
            return count != null ? count : 0;
        }, userId);
    }

    // ========== WordPress 用户资料管理 ==========

    @Override
    public boolean updateDisplayName(Object userId, String displayName) {
        return executeWithBooleanLogging("updateDisplayName", () -> {
            validateNotNull(userId, "用户ID不能为空");
            validateNotBlank(displayName, "显示名称不能为空");

            Users user = getById(userId);
            if (user == null) {
                return false;
            }

            user.setDisplayName(displayName);
            return update(user);
        }, userId, displayName);
    }

    @Override
    public boolean updateNickname(BigInteger userId, String nickname) {
        return executeWithBooleanLogging("updateNickname", () -> {
            validateNotNull(userId, "用户ID不能为空");
            validateNotBlank(nickname, "昵称不能为空");

            Usermeta meta = new Usermeta();
            meta.setUserId(userId);
            meta.setMetaKey("nickname");
            meta.setMetaValue(nickname);

            return saveOrUpdateUsermeta(meta);
        }, userId, nickname);
    }

    @Override
    public boolean updateWebsite(Object userId, String website) {
        return executeWithBooleanLogging("updateWebsite", () -> {
            validateNotNull(userId, "用户ID不能为空");

            Users user = getById(userId);
            if (user == null) {
                return false;
            }

            user.setUserUrl(website);
            return update(user);
        }, userId, website);
    }

    @Override
    public boolean updateDescription(BigInteger userId, String description) {
        return executeWithBooleanLogging("updateDescription", () -> {
            validateNotNull(userId, "用户ID不能为空");

            Usermeta meta = new Usermeta();
            meta.setUserId(userId);
            meta.setMetaKey("description");
            meta.setMetaValue(description);

            return saveOrUpdateUsermeta(meta);
        }, userId, description);
    }

    @Override
    public boolean updateAvatar(BigInteger userId, String avatarUrl) {
        return executeWithBooleanLogging("updateAvatar", () -> {
            validateNotNull(userId, "用户ID不能为空");
            validateNotBlank(avatarUrl, "头像URL不能为空");

            Usermeta meta = new Usermeta();
            meta.setUserId(userId);
            meta.setMetaKey("avatar_url");
            meta.setMetaValue(avatarUrl);

            return saveOrUpdateUsermeta(meta);
        }, userId, avatarUrl);
    }

    // ========== WordPress 系统维护 ==========

    @Override
    public int cleanupExpiredUsers(int days) {
        return executeWithResultLogging("cleanupExpiredUsers", () -> {
            String sql = "DELETE FROM " + getTableName() +
                    " WHERE user_status = 0 AND user_registered < DATE_SUB(NOW(), INTERVAL ? DAY)";

            int result = Db.delete(sql, days);
            log.info("清理过期用户完成: 删除了{}个用户", result);
            return result;
        }, days);
    }

    @Override
    public String regenerateActivationKey(Object userId) {
        return executeWithResultLogging("regenerateActivationKey", () -> {
            validateNotNull(userId, "用户ID不能为空");

            String activationKey = UUID.randomUUID().toString().replace("-", "");

            Users user = getById(userId);
            if (user != null) {
                user.setUserActivationKey(activationKey);
                if (update(user)) {
                    return activationKey;
                }
            }

            return "";
        }, userId);
    }

    @Override
    public boolean syncUserMetadata(BigInteger userId) {
        return executeWithBooleanLogging("syncUserMetadata", () -> {
            validateNotNull(userId, "用户ID不能为空");

            Users user = getById(userId);
            if (user == null) {
                return false;
            }

            // 同步显示名称和昵称
            if (StrKit.isBlank(user.getDisplayName())) {
                user.setDisplayName(user.getUserLogin());
                update(user);
            }

            // 确保昵称元数据存在
            String nickname = getUserMetaValue(userId, "nickname");
            if (StrKit.isBlank(nickname)) {
                updateNickname(userId, user.getDisplayName());
            }

            return true;
        }, userId);
    }

    @Override
    public boolean validateUserData(Object userId) {
        return executeWithBooleanLogging("validateUserData", () -> {
            validateNotNull(userId, "用户ID不能为空");

            Users user = getById(userId);
            if (user == null) {
                return false;
            }

            // 基本数据验证
            if (StrKit.isBlank(user.getUserLogin())) return false;
            if (StrKit.isBlank(user.getUserEmail())) return false;
            if (user.getUserRegistered() == null) return false;

            // 邮箱格式验证
            if (!isValidEmail(user.getUserEmail())) return false;

            return true;
        }, userId);
    }

    @Override
    public boolean repairUserData(Object userId) {
        return executeWithBooleanLogging("repairUserData", () -> {
            validateNotNull(userId, "用户ID不能为空");

            Users user = getById(userId);
            if (user == null) {
                return false;
            }

            boolean repaired = false;

            // 修复显示名称
            if (StrKit.isBlank(user.getDisplayName())) {
                user.setDisplayName(user.getUserLogin());
                repaired = true;
            }

            // 修复昵称
            if (StrKit.isBlank(user.getUserNicename())) {
                user.setUserNicename(user.getUserLogin());
                repaired = true;
            }

            if (repaired) {
                return update(user);
            }

            return true;
        }, userId);
    }

    // ========== WordPress 特定功能 ==========

    @Override
    public String getUserAvatarUrl(Object userId, Integer size) {
        return executeWithResultLogging("getUserAvatarUrl", () -> {
            validateNotNull(userId, "用户ID不能为空");

            // 首先检查自定义头像
            String customAvatar = getUserMetaValue(userId, "avatar_url");
            if (StrKit.notBlank(customAvatar)) {
                return customAvatar;
            }

            // 使用Gravatar
            Users user = getById(userId);
            if (user != null) {
                String email = user.getUserEmail();
                String hash = md5(email.toLowerCase().trim());
                String sizeParam = size != null ? "?s=" + size : "";
                return "https://www.gravatar.com/avatar/" + hash + sizeParam;
            }

            return "";
        }, userId, size);
    }

    @Override
    public String getUserLocale(Object userId) {
        return executeWithResultLogging("getUserLocale", () -> {
            validateNotNull(userId, "用户ID不能为空");

            String locale = getUserMetaValue(userId, "locale");
            return StrKit.notBlank(locale) ? locale : "en_US";
        }, userId);
    }

    @Override
    public boolean setUserLocale(BigInteger userId, String locale) {
        return executeWithBooleanLogging("setUserLocale", () -> {
            validateNotNull(userId, "用户ID不能为空");
            validateNotBlank(locale, "本地化代码不能为空");

            Usermeta meta = new Usermeta();
            meta.setUserId(userId);
            meta.setMetaKey("locale");
            meta.setMetaValue(locale);

            return saveOrUpdateUsermeta(meta);
        }, userId, locale);
    }

    @Override
    public String getAdminColorScheme(Object userId) {
        return executeWithResultLogging("getAdminColorScheme", () -> {
            validateNotNull(userId, "用户ID不能为空");

            String scheme = getUserMetaValue(userId, "admin_color");
            return StrKit.notBlank(scheme) ? scheme : "fresh";
        }, userId);
    }

    @Override
    public boolean setAdminColorScheme(BigInteger userId, String colorScheme) {
        return executeWithBooleanLogging("setAdminColorScheme", () -> {
            validateNotNull(userId, "用户ID不能为空");
            validateNotBlank(colorScheme, "颜色方案不能为空");

            Usermeta meta = new Usermeta();
            meta.setUserId(userId);
            meta.setMetaKey("admin_color");
            meta.setMetaValue(colorScheme);

            return saveOrUpdateUsermeta(meta);
        }, userId, colorScheme);
    }

    @Override
    public String getUserTimezone(Object userId) {
        return executeWithResultLogging("getUserTimezone", () -> {
            validateNotNull(userId, "用户ID不能为空");

            String timezone = getUserMetaValue(userId, "timezone");
            return StrKit.notBlank(timezone) ? timezone : "UTC+0";
        }, userId);
    }

    @Override
    public boolean setUserTimezone(BigInteger userId, String timezone) {
        return executeWithBooleanLogging("setUserTimezone", () -> {
            validateNotNull(userId, "用户ID不能为空");
            validateNotBlank(timezone, "时区不能为空");

            Usermeta meta = new Usermeta();
            meta.setUserId(userId);
            meta.setMetaKey("timezone");
            meta.setMetaValue(timezone);

            return saveOrUpdateUsermeta(meta);
        }, userId, timezone);
    }

    @Override
    public String getUserDateFormat(Object userId) {
        return executeWithResultLogging("getUserDateFormat", () -> {
            validateNotNull(userId, "用户ID不能为空");

            String dateFormat = getUserMetaValue(userId, "date_format");
            return StrKit.notBlank(dateFormat) ? dateFormat : "Y-m-d";
        }, userId);
    }

    @Override
    public boolean setUserDateFormat(BigInteger userId, String dateFormat) {
        return executeWithBooleanLogging("setUserDateFormat", () -> {
            validateNotNull(userId, "用户ID不能为空");
            validateNotBlank(dateFormat, "日期格式不能为空");

            Usermeta meta = new Usermeta();
            meta.setUserId(userId);
            meta.setMetaKey("date_format");
            meta.setMetaValue(dateFormat);

            return saveOrUpdateUsermeta(meta);
        }, userId, dateFormat);
    }

    @Override
    public String getUserTimeFormat(Object userId) {
        return executeWithResultLogging("getUserTimeFormat", () -> {
            validateNotNull(userId, "用户ID不能为空");

            String timeFormat = getUserMetaValue(userId, "time_format");
            return StrKit.notBlank(timeFormat) ? timeFormat : "H:i";
        }, userId);
    }

    @Override
    public boolean setUserTimeFormat(BigInteger userId, String timeFormat) {
        return executeWithBooleanLogging("setUserTimeFormat", () -> {
            validateNotNull(userId, "用户ID不能为空");
            validateNotBlank(timeFormat, "时间格式不能为空");

            Usermeta meta = new Usermeta();
            meta.setUserId(userId);
            meta.setMetaKey("time_format");
            meta.setMetaValue(timeFormat);

            return saveOrUpdateUsermeta(meta);
        }, userId, timeFormat);
    }

    @Override
    public Integer getUserStartOfWeek(Object userId) {
        return executeWithResultLogging("getUserStartOfWeek", () -> {
            validateNotNull(userId, "用户ID不能为空");

            String startOfWeek = getUserMetaValue(userId, "start_of_week");
            if (StrKit.notBlank(startOfWeek)) {
                try {
                    return Integer.parseInt(startOfWeek);
                } catch (NumberFormatException e) {
                    log.warn("解析起始星期失败: " + startOfWeek);
                }
            }
            return 1; // 默认星期一
        }, userId);
    }

    @Override
    public boolean setUserStartOfWeek(BigInteger userId, Integer startOfWeek) {
        return executeWithBooleanLogging("setUserStartOfWeek", () -> {
            validateNotNull(userId, "用户ID不能为空");
            validateNotNull(startOfWeek, "起始星期不能为空");

            if (startOfWeek < 0 || startOfWeek > 6) {
                throw new IllegalArgumentException("起始星期必须在0-6之间");
            }

            Usermeta meta = new Usermeta();
            meta.setUserId(userId);
            meta.setMetaKey("start_of_week");
            meta.setMetaValue(startOfWeek.toString());

            return saveOrUpdateUsermeta(meta);
        }, userId, startOfWeek);
    }

    // ========== 用户权限验证 ==========

    @Override
    public boolean checkUserPermission(Object userId, String operation) {
        return executeWithBooleanLogging("checkUserPermission", () -> {
            validateNotNull(userId, "用户ID不能为空");
            validateNotBlank(operation, "操作名称不能为空");

            // 根据操作名称检查权限
            switch (operation.toLowerCase()) {
                case "create_post":
                case "edit_post":
                case "delete_post":
                    return hasCapability(userId, "edit_posts");
                case "create_page":
                case "edit_page":
                case "delete_page":
                    return hasCapability(userId, "edit_pages");
                case "moderate_comments":
                    return hasCapability(userId, "moderate_comments");
                case "manage_users":
                    return hasCapability(userId, "list_users");
                case "manage_options":
                    return hasCapability(userId, "manage_options");
                default:
                    return hasCapability(userId, operation);
            }
        }, userId, operation);
    }

    @Override
    public List<String> getUserPermissions(Object userId) {
        return getUserCapabilities(userId);
    }

    @Override
    public boolean checkDataAccessPermission(Object userId, String dataType, Long dataId) {
        return executeWithBooleanLogging("checkDataAccessPermission", () -> {
            validateNotNull(userId, "用户ID不能为空");
            validateNotBlank(dataType, "数据类型不能为空");
            validateNotNull(dataId, "数据ID不能为空");

            String userRole = getUserRole(userId);

            // 管理员可以访问所有数据
            if ("administrator".equals(userRole)) {
                return true;
            }

            switch (dataType.toLowerCase()) {
                case "post":
                    // 检查是否是自己的文章或者是可以编辑其他人的文章
                    if (hasCapability(userId, "edit_others_posts")) {
                        return true;
                    }
                    String postSql = "SELECT post_author FROM " + POSTS_TABLE + " WHERE ID = ?";
                    Record post = Db.findFirst(postSql, dataId);
                    return post != null && userId.equals(post.get("post_author"));

                case "page":
                    if (hasCapability(userId, "edit_others_pages")) {
                        return true;
                    }
                    String pageSql = "SELECT post_author FROM " + POSTS_TABLE + " WHERE ID = ? AND post_type = 'page'";
                    Record page = Db.findFirst(pageSql, dataId);
                    return page != null && userId.equals(page.get("post_author"));

                default:
                    return false;
            }
        }, userId, dataType, dataId);
    }

    // ========== 用户会话管理 ==========

    @Override
    public List<Map<String, Object>> getUserActiveSessions(Object userId) {
        return executeWithResultLogging("getUserActiveSessions", () -> {
            validateNotNull(userId, "用户ID不能为空");

            String sessionTokens = getUserMetaValue(userId, "session_tokens");
            List<Map<String, Object>> sessions = new ArrayList<>();

            if (StrKit.notBlank(sessionTokens)) {
                try {
                    // 简化解析会话令牌
                    // 实际格式是序列化的PHP数组
                    String[] tokenEntries = sessionTokens.split(";");
                    for (String entry : tokenEntries) {
                        if (entry.contains(":")) {
                            String[] parts = entry.split(":");
                            if (parts.length >= 2) {
                                Map<String, Object> session = new HashMap<>();
                                session.put("token", parts[0]);
                                session.put("login_time", parts[1]);
                                sessions.add(session);
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("解析用户会话失败", e);
                }
            }

            return sessions;
        }, userId);
    }

    @Override
    public boolean terminateUserSession(Object userId, String sessionId) {
        return executeWithBooleanLogging("terminateUserSession", () -> {
            validateNotNull(userId, "用户ID不能为空");
            validateNotBlank(sessionId, "会话ID不能为空");

            // 简化实现：清除所有会话
            return deleteUserMeta(userId, "session_tokens");
        }, userId, sessionId);
    }

    @Override
    public boolean terminateAllUserSessions(Object userId) {
        return clearUserSessions(userId);
    }

    // ========== 用户导入导出 ==========

    @Override
    public Map<String, Object> exportUserData(Object userId) {
        return executeWithResultLogging("exportUserData", () -> {
            validateNotNull(userId, "用户ID不能为空");

            Users user = getById(userId);
            if (user == null) {
                return Collections.emptyMap();
            }

            Map<String, Object> userData = new HashMap<>();

            // 基本用户信息
            userData.put("id", user.get("ID"));
            userData.put("user_login", user.getUserLogin());
            userData.put("user_email", user.getUserEmail());
            userData.put("display_name", user.getDisplayName());
            userData.put("user_registered", user.getUserRegistered());
            userData.put("user_status", user.getUserStatus());

            // 用户元数据
            List<Usermeta> metas = getUserMetas(userId);
            Map<String, String> metaData = new HashMap<>();
            for (Usermeta meta : metas) {
                metaData.put(meta.getMetaKey(), meta.getMetaValue());
            }
            userData.put("meta_data", metaData);

            // 用户统计
            userData.put("post_count", getUserPostCount(userId));
            userData.put("comment_count", getUserCommentCount(userId));

            return userData;
        }, userId);
    }

    @Override
    public Object importUserData(Map<String, Object> userData) {
        return executeWithResultLogging("importUserData", () -> {
            validateNotNull(userData, "用户数据不能为空");

            Users user = new Users();

            // 设置基本字段
            if (userData.containsKey("user_login")) {
                user.setUserLogin(userData.get("user_login").toString());
            }
            if (userData.containsKey("user_email")) {
                user.setUserEmail(userData.get("user_email").toString());
            }
            if (userData.containsKey("display_name")) {
                user.setDisplayName(userData.get("display_name").toString());
            }
            if (userData.containsKey("user_registered")) {
                Object regDate = userData.get("user_registered");
                if (regDate instanceof Date) {
                    user.setUserRegistered((Date) regDate);
                }
            }

            // 设置默认值
            if (user.getUserRegistered() == null) {
                user.setUserRegistered(new Date());
            }
            if (user.getUserStatus() == null) {
                user.setUserStatus(0);
            }

            // 保存用户
            boolean success = user.save();
            if (!success) {
                return null;
            }

            BigInteger newUserId = user.getID();

            // 导入元数据
            if (userData.containsKey("meta_data")) {
                @SuppressWarnings("unchecked")
                Map<String, String> metaData = (Map<String, String>) userData.get("meta_data");
                batchUpdateUserMetas(newUserId, metaData);
            }

            return newUserId;
        }, userData.size());
    }

    @Override
    public List<Map<String, Object>> batchExportUserData(List<Object> userIds) {
        return executeWithResultLogging("batchExportUserData", () -> {
            if (userIds == null || userIds.isEmpty()) {
                return Collections.emptyList();
            }

            List<Map<String, Object>> result = new ArrayList<>();
            for (Object userId : userIds) {
                Map<String, Object> userData = exportUserData(userId);
                if (!userData.isEmpty()) {
                    result.add(userData);
                }
            }

            return result;
        }, userIds.size());
    }

    // ========== 私有工具方法 ==========

    /**
     * 更新用户能力列表
     */
    private boolean updateCapabilities(BigInteger userId, List<String> capabilities) {
        StringBuilder jsonBuilder = new StringBuilder("{");
        for (int i = 0; i < capabilities.size(); i++) {
            if (i > 0) {
                jsonBuilder.append(",");
            }
            jsonBuilder.append("\"").append(capabilities.get(i)).append("\":true");
        }
        jsonBuilder.append("}");

        Usermeta meta = new Usermeta();
        meta.setUserId(userId);
        meta.setMetaKey("wp_capabilities");
        meta.setMetaValue(jsonBuilder.toString());

        return saveOrUpdateUsermeta(meta);
    }

    /**
     * 验证邮箱格式
     */
    private boolean isValidEmail(String email) {
        if (StrKit.isBlank(email)) {
            return false;
        }
        return email.matches("^[A-Za-z0-9+_.-]+@(.+)$");
    }

    /**
     * MD5加密（简化实现）
     */
    private String md5(String input) {
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            byte[] array = md.digest(input.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : array) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (java.security.NoSuchAlgorithmException e) {
            return "";
        }
    }
}